// pages/home/home.js
const app = getApp();
const QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
// 实例化API核心类
var mapLocation = new QQMapWX({
  key: 'ZWHBZ-CL5KG-RI6QY-IAYDI-UT725-AIFF5' // 必填
});

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: "1",
    scale: 16,
    markers: [],
    pageIndex: 1,  // 第几页
    // mapPageIndex: 1,  // 第几页
    tabActive: "one",
    cinemaList: [], // 影院列表
    locationCity: "",  // 城市
    city: "",     // 选择城市
    province: "", // 省份
    latitude: "", // 纬度  
    longitude: "", // 经度
    nomore: false,
    nomoreMap: false,
    markerMap: false,
    isGetList: false,
    isSelect: false,
    animationData: {},
    provinceList: [],   // 省份列表
    cityList: [],       // 城市列表
    currentIndex: "",   // 当前省份的下标
  },

 
  // 点击地图坐标进入详情
  markertap: function(e) {
    var cinemaId = e.markerId.split(",")[0];
    var listType = e.markerId.split(",")[1];
    var distance = e.markerId.split(",")[2];
    if (distance < 1000) {
      distance = distance + "m";
    } else {
      distance = Number(distance / 1000).toFixed(2) + "km";
    }
    if (listType == "1"){
      app.globalData.cinemaId = cinemaId;
      app.globalData.cinemaDistance = distance;
      wx.navigateTo({
        url: '../cinemaDetail/cinemaDetail',
      })
    }else{}
  },

  // 从列表去详情页面
  goDetail: function (e) {
    app.globalData.cinemaId = e.currentTarget.dataset.id;
    app.globalData.cinemaDistance = e.currentTarget.dataset.distance;
    wx.navigateTo({
      url: '../cinemaDetail/cinemaDetail',
    })
  },

  // tab切换
  changeTab: function(e){
    if (e.currentTarget.dataset.index == "1"){
      wx.pageScrollTo({
        scrollTop: 0
      });
    }else{
      if(this.data.isGetList == false){
        this.getList();
      }
    }
    this.setData({
      currentTab: e.currentTarget.dataset.index
    });
  },

  // 改变城市
  changeCity: function(){
    this.maskAnimation();
    this.setData({
      currentIndex: 0,
    })
  },

  // 动画
  maskAnimation: function () {
    // 用that取代this，防止不必要的情况发生
    var that = this;
    // 创建一个动画实例
    var animation = wx.createAnimation({
      // 动画持续时间
      duration: 500,
      // 定义动画效果
      timingFunction: 'ease'
    })
    // 将该变量赋值给当前动画
    that.animation = animation
    // 先在y轴偏移，然后用step()完成一个动画
    animation.translateY(200).step();
    // 用setData改变当前动画
    that.setData({
      // 通过export()方法导出数据
      animationData: animation.export(),
      // 改变view里面的Wx：if
      isSelect: !that.data.isSelect,
    })
    // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
    setTimeout(function () {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export()
      })
    }, 100);

    // 添加省份
    this.getProvince();
  },

  // 获取省份列表
  getProvince: function () {
    wx.request({
      url: app.globalData.url + '/linkage/list',
      method: "POST",
      data: {
        "access_token": app.globalData.token,
      },
      success: res => {
        if (res.data.err_code == "200") {
          if (res.data.data.linkpage_list.length > 0) {
            this.setData({
              provinceList: res.data.data.linkpage_list,
              cityList: res.data.data.linkpage_list[0].children,
              province: res.data.data.linkpage_list[0].name,
              city: ""
            });
          }
        }
      },
      fail: res => {
        console.log(res);
      }
    })
  },

  // 获取省份对应的城市列表
  changeProvince: function (e) {
    var index = e.currentTarget.dataset.index;
    var provinceList = this.data.provinceList;
    this.setData({
      cityList: provinceList[index].children,
      province: provinceList[index].name,
      city: "",
      locationCity: provinceList[index].name,
      currentIndex: index
    });
  },

  // 选择城市
  selectCity: function(e){
    this.setData({
      city: e.currentTarget.dataset.city,
      locationCity: e.currentTarget.dataset.city
    });
  },

  // 点击确定
  sureSelect: function(){
    this.hideMask();
    if(this.data.city != ""){
      this.getLocation(this.data.city);
      this.setData({
        locationCity: this.data.city,
      });
    }else{
      this.setData({
        city: "",
        latitude: this.data.provinceList[this.data.currentIndex].tencent_lat,
        longitude: this.data.provinceList[this.data.currentIndex].tencent_lon,
        locationCity: this.data.provinceList[this.data.currentIndex].name,
      });
    }
    this.getMapList();
    this.getList();
  },

  // 地址转坐标
  getLocation: function (address) {
    mapLocation.geocoder({
      address: address,
      success: res => {
        this.setData({
          latitude: res.result.location.lat,
          longitude: res.result.location.lng,
        });
      },
      fail: res => {
        console.log(res);
      }
    });
  },

  // 关闭时间选择弹框
  hideMask: function () {
    var that = this;
    that.setData({
      selectWeek: []
    })
    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease'
    })
    that.animation = animation
    animation.translateY(200).step()
    that.setData({
      animationData: animation.export()
    })
    setTimeout(function () {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export(),
        isSelect: false
      })
    }, 200);
  },

  
  // 获取影院列表
  getList: function(){
    wx.showLoading({
      title: '加载中',
    })
    this.setData({
      cinemaList: []
    });
    wx.request({
      url: app.globalData.url + '/cinema/list',
      method: "POST",
      async: false,
      data: {
        "access_token": app.globalData.token,
        "city_name": this.data.city,
        "province_name": this.data.province,
        "page": "1",
        "pageSize": "999",
        "current_lon": this.data.longitude,
        "current_lat": this.data.latitude,
        "zoom": 16
      },
      success: res => {
        this.setData({
          isGetList: true
        })
        if (res.data.err_code == "200"){
          var cinemaList = res.data.data.cinema_list.data;
          if (cinemaList.length === 0){
            this.setData({
              nomore: true
            })
          }else{
            var cinemaAllList = [];
            for (var i = 0; i < cinemaList.length; i ++){
              var listType = cinemaList[i].type;
              if (listType == "1"){
                cinemaAllList.push(cinemaList[i]);
              }else{}
            }
            for (var i = 0; i < cinemaAllList.length; i ++){
              var distance = cinemaAllList[i].distance;
              if (distance < 1000){
                cinemaAllList[i].distance = distance + "m";
              }else{
                cinemaAllList[i].distance = Number(distance / 1000).toFixed(2) + "km";
              }
            }
            this.setData({
              cinemaList: this.data.cinemaList.concat(cinemaAllList)
            });
          }
          wx.hideLoading();
        }
      },
      fail: res => {
        console.log(res);
        app.showError("请求超时");
      }
    });
  },


  // 获取地图信息
  getMapList: function(){
    wx.showLoading({
      title: '加载中',
    })
    this.setData({
      markers: [],
      markerMap: false
    });
    wx.request({
      url: app.globalData.url + '/cinema/list',
      method: "POST",
      async: false,
      data: {
        "access_token": app.globalData.token,
        "city_name": this.data.city,
        "province_name": this.data.province,
        "page": "1",
        "pageSize": "999",
        "current_lon": this.data.longitude,
        "current_lat": this.data.latitude,
        "zoom": this.data.scale
      },
      success: res => {
        if (res.data.err_code == "200") {
          var cinemaList = res.data.data.cinema_list.data;
          if (cinemaList.length === 0) {
            this.setData({
              markerMap: true
            })
          } else {
            var markersData = [];
            markersData.length = cinemaList.length;
            for (var i = 0; i < cinemaList.length; i++) {
              var latitude, longitude, content, bgColor, cinemaId;
              latitude = Number(cinemaList[i].tencent_lat);
              longitude = Number(cinemaList[i].tencent_lon);
              content = cinemaList[i].cinema_name + "\n" + "xxxxx人";
              if (cinemaList[i].type == "1"){
                bgColor = "#3a74fe";
                cinemaId = cinemaList[i].id + "," + cinemaList[i].type + "," + cinemaList[i].distance;
              } else{
                cinemaId = i + "," + cinemaList[i].type + "," + cinemaList[i].distance;
                if (cinemaList[i].type == "2"){
                  bgColor = "#6ce191";
                } else if (cinemaList[i].type == "3"){
                  bgColor = "#fe4f76";
                } else if (cinemaList[i].type == "4") {
                  bgColor = "#feb544";
                }else{}
              }
              markersData[i] = {
                iconPath: "../../images/dot.png",
                id: cinemaId,
                latitude: latitude,
                longitude: longitude,
                width: 5,
                height: 5,
                bgColor: "#fff",
                callout: {
                  content: content,
                  color: '#fff',
                  fontSize: 12,
                  borderRadius: 16,
                  display: 'ALWAYS',
                  bgColor: bgColor,
                  padding: 10,
                  textAlign: "center"
                },
              }
            }
            this.setData({
              markers: this.data.markers.concat(markersData),
            });
            if (this.data.markers.length > 0) {
              this.setData({
                markerMap: true
              });
            }
          }
          wx.hideLoading();
        }
      },
      fail: res => {
        console.log(res);
        app.showError("请求超时");
      }
    });
  },

  // 列表下拉加载更多 
  // moreCinema: function () {
  //   if (!this.data.nomore) {
  //     this.setData({
  //       pageIndex: parseInt(this.data.pageIndex) + 1
  //     })
  //     this.getList();
  //   }
  // },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.mapCtx = wx.createMapContext('map'); // 获取地图
    this.setData({
      latitude: app.globalData.latitude,
      longitude: app.globalData.longitude,
      city: app.globalData.chooseCity,
      locationCity: app.globalData.chooseCity,
      province: app.globalData.chooseProvince
    });
    this.getMapList();
  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // if(this.data.currentTab == "2"){
    //   this.moreCinema();
    // }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.mapCtx = wx.createMapContext('map'); // 获取地图
    // this.setData({
    //   latitude: app.globalData.latitude,
    //   longitude: app.globalData.longitude,
    // });
    // this.getMapList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '',
      path: '/page/index/index'
    }
  }
})